﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using SpLocalizer.Common;
using Microsoft.SharePoint;
using System.Xml;

namespace SpLocalizer.ContentSourceProviders.SpDocumentLibraryFile
{
    internal abstract class AbstractFileLocalizationTask : BaseTranslationTask
    {

        #region Constants
        
        private const string Property_ItemId = "ItemId";

        #endregion

         /// <summary>
        /// Respource key 
        /// </summary>
        public Guid ItemId
        {
            get { return new Guid(this.GetPropertyValue(Property_ItemId)); }
            set { this.SetPropertyValue(Property_ItemId, value.ToString()); }
        }


        /// <summary>
        /// Constructor without parameters should be public for unity injection
        /// </summary>
        public AbstractFileLocalizationTask () { }

        /// <summary>
        /// Initialize translation task from content source object
        /// </summary>
        /// <param name="FromLanguage"></param>
        /// <param name="ToLanguage"></param>
        /// <param name="item"></param>
        internal void InitializeTask(CultureInfo FromLanguage, CultureInfo ToLanguage, 
            SPListItem item) 
        {
            this.ItemId = item.UniqueId;            
            this.SourceText = GetDocumentXmlToTranslate(item);
            this.Status = TranslationTaskStatus.Initialized;
            this.Format = Path.GetExtension(item.File.Name).ToLower();
            this.FromLanguage = FromLanguage;
            this.ToLanguage = ToLanguage;
        }

        /// <summary>
        /// Export OpenXml document to the task string for translation
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        protected abstract string GetDocumentXmlToTranslate(SPListItem item);

        /// <summary>
        /// Export translation task back to the content source
        /// </summary>
        /// <param name="item"></param>
        internal abstract void ExportTranslation(SPListItem item);


        protected void SafeFile(SPFile theFile, Stream documentStream)
        {
            if (theFile.CheckOutType == SPFile.SPCheckOutType.None)
            {
                theFile.CheckOut();
            }
            theFile.SaveBinary(documentStream);
            theFile.Update();
            theFile.CheckIn("Automatic translation for document");
        }
    }
}
